//
//  ChargeReportedViewController.m
//  Runone
//
//  Created by ekkaLyn on 2017/3/15.
//  Copyright © 2017年 runone. All rights reserved.
//  收费事件上报

#import "ChargeReportedViewController.h"
#import "RequestHelper.h"
#import "MJExtension.h"
#import "ParModel.h"
#import "EventBaseInfo.h"
#import "MapPointViewController.h"
#import "CityDirectionController.h"
#import "TableOperation.h"
#import "PileInfo.h"
#import "CommonUtilityjudge.h"
#import "SGImagePickerController.h"
//#import "UIColor+ZXLazy.h"
#import "SVProgressHUD.h"
#import "BCNetAPIClient.h"
#import "LittleVideoViewController.h"
#import "ROActionSheet.h"
#import "ChooseLineTableViewController.h"
#import "ROImagePickViewController.h"
#import "AJPhotoPickerViewController.h"
#import "AJPhotoBrowserViewController.h"
#import "OtherEventMainLineViewController.h"
#import "HighWayRoadRecordDirectionInfoModel.h"

#import "ChooseDirectionView.h"
#import "SDAutoLayout.h"
#import "ChoosePileNOView.h"
#import "UnStartEventView.h"
#import "InProgressPicAndVideoView.h"
#import "PhotoesScrollView.h"
#import "StationRrportModel.h"
#import "POPDatePickViewController.h"
#import "DateViewController.h"
#import "StationListPopViewController.h"
#import "EventTypeTableViewController.h"
#import "BDMTollEventTypeDefineInfoModel.h"
#import "StationListPopViewController.h"
#import "InProgressConstructPositionView.h"
#import "ChooseTimeView.h"
#import "UIButton+ROCameraPhotoes.h"
#import "DropDownBackView.h"
#import "DrowDownViewController.h"
#import "AppDelegate.h"
#import "RODateHelper.h"
#import "NSDate+ROCaculateTime.h"
#import "UIColor+Addition.h"
#import "EKDateTimePickerView.h"
#import "NSDate+Extension.h"
#import "Define.h"

@interface ChargeReportedViewController ()<UIScrollViewDelegate, LittleVideoDelegate,AJPhotoPickerProtocol, AJPhotoBrowserDelegate, UIImagePickerControllerDelegate,UINavigationControllerDelegate, UIAlertViewDelegate, UIPopoverPresentationControllerDelegate>{
    AVPlayer *_player;
    AVPlayerItem *_playItem;
    AVPlayerLayer *_playerLayer;
    AVPlayerLayer *_fullPlayer;
    BOOL _isPlaying;
}
@property (nonatomic, strong) UIScrollView                    *scroollView;
@property (nonatomic, strong) UIView                          *wrapperView;
@property (nonatomic, strong) UIView                          *containerV;
@property (nonatomic, strong) PhotoesScrollView               *photoesV;          //选中的图片的view
@property (nonatomic, strong) ChooseDirectionView            *stationV;       // 收费站
@property (nonatomic, strong) InProgressConstructPositionView             *eventTypeV;            // 事件类型
@property (nonatomic, strong) UnStartEventView               *dutyStationmaster;  // 值班站长
@property (nonatomic, strong) UnStartEventView          *eventDescripV;      // 发生事件
@property (nonatomic, strong) ChooseDirectionView    *timeView;        // 事件描述
@property (nonatomic, strong) InProgressPicAndVideoView *picAndVideoV; // 图片视频按钮

@property (nonatomic, strong) UIView                          *videoView;
@property (nonatomic, strong) NSURL                           *videoUrl;
@property(nonatomic,strong) DateViewController                *dateVC;
@property(nonatomic,strong) EventTypeTableViewController      *eventVC;
@property(nonatomic,strong) StationRrportModel                *StationModel;
@property(nonatomic,strong) POPDatePickViewController         *popdate;
@property(nonatomic,strong) BDMTollEventTypeDefineInfoModel   *currentTemplateModel;
@property (nonatomic, strong) NSMutableArray                  *selectPhoteArray;//选中图片

@property(nonatomic,strong)StationListPopViewController *station;

@property (assign, nonatomic) NSInteger typeInt;
@property (nonatomic, assign) NSInteger isFirstTime;
@property (nonatomic, strong) NSDate *lastScrollDate;// 上一次滚动的时间
@end

@implementation ChargeReportedViewController

 #pragma   ------------收费事件上报

- (UIScrollView *)scroollView {
    if (!_scroollView) {
        _scroollView = [UIScrollView new];
        _scroollView.delegate = self;
        _scroollView.bounces  = NO;
        [self.view addSubview:_scroollView];
        _scroollView.showsVerticalScrollIndicator = YES;
        _scroollView.showsHorizontalScrollIndicator = NO;
        _scroollView.sd_layout
        .topSpaceToView(self.view, 0)
        .leftSpaceToView(self.view, 0)
        .rightSpaceToView(self.view, 0)
        .bottomSpaceToView(self.view, 0);
    }
    return _scroollView;
}
- (PhotoesScrollView *)photoesV {
    if (!_photoesV) {
        PhotoesScrollView *photoesV = [[PhotoesScrollView alloc] init];
        _photoesV = photoesV;
        [self.containerV addSubview:_photoesV];
        self.photoesV.sd_layout
        .widthIs([UIScreen mainScreen].bounds.size.width - 16)
        .heightIs(100)
        .topSpaceToView(self.eventDescripV, 10)
        .centerXEqualToView(self.containerV)
        ;
    }
    return _photoesV;
}
- (UIView *)videoView {
    if (!_videoView) {
        UIView *newView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width - 20, 200)];
        _videoView = newView;
//        newView.backgroundColor = [UIColor yellowColor];
        [self.containerV addSubview:_videoView];
        
    }
    return _videoView;
}




- (void)viewDidLoad {
    [super viewDidLoad];
    
    _currentTemplateModel = [[BDMTollEventTypeDefineInfoModel alloc] init];
    _StationModel                     = [[StationRrportModel alloc] init];
    _station                          = [[StationListPopViewController alloc] init];
    _station.modalPresentationStyle   = UIModalPresentationPopover;
    __weak typeof(self) stationSelf = self;
    _station.LineBlock=^(StationModel *model){
        stationSelf.stationV.directionLabel.text              =[NSString stringWithFormat:@"%@",model.TollStationName];
        stationSelf.StationModel.TollStationUID = model.TollStationUID;
    };
  
  
    [self setUpNavigationBar];
    [self setUpUI];
    [self setUpArray];
    }

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    
}
//设置标题
- (void) setUpNavigationBar {
    UILabel *label                = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
    label.text                    = @"收费事件上报";
    label.textAlignment           = NSTextAlignmentCenter;
    label.textColor               = [UIColor whiteColor];
    self.navigationItem.titleView = label;
    
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"提 交" style:UIBarButtonItemStylePlain target:self action:@selector(report)];
}

//提交事件判断
- (void)report{
    if (self.stationV.directionLabel.text.length == 0) {
        [SVProgressHUD showSuccessWithStatus:@"请选择收费站"];
        return;
    }
    if (self.eventTypeV.middelLabel.text.length == 0) {
        [SVProgressHUD showSuccessWithStatus:@"请输入事件类型"];
        return;
    }
    if (self.dutyStationmaster.desTextV.text.length == 0) {
        [SVProgressHUD showSuccessWithStatus:@"值班站长不能为空"];
        return;
    }
    if (self.timeView.directionLabel.text.length == 0) {
        [SVProgressHUD showSuccessWithStatus:@"请输入发生时间"];
        return;
    }
    if (self.eventDescripV.desTextV.text.length == 0) {
        [SVProgressHUD showSuccessWithStatus:@"请输入事件描述"];
        return;
    }
    
    if (self.eventDescripV.desTextV.text.length > 1000) {
        [SVProgressHUD showSuccessWithStatus:@"事件描述不能超过1000字"];
        return;
    }
    
    NSDate *beginDate = [RODateHelper dateFromString:self.timeView.directionLabel.text withFormat:nil];
    NSInteger beginInter = [beginDate compareToCurrentDate];
    if (beginInter == 1) {
//        [_Prompt alert:@"开始时间不能大于当前时间"];
        return;
    }
    [self request];
}

//
- (void) request {
    [SVProgressHUD showWithStatus:@"正在上报..."];
    RequestGinsengModel *getCurrentEventModel=[[RequestGinsengModel alloc] init];
    getCurrentEventModel.URL=GetEventDataURL;
    getCurrentEventModel.DataValue = [self dataValueJson];
    getCurrentEventModel.UpdatedTime=@"";
    getCurrentEventModel.SystemCode=@"GuangleHighway";
    getCurrentEventModel.MethodName=@"ReportTollStationEventDetailInfo";
    
    NSDictionary *dic=[[NSDictionary alloc] init];
    dic = @{@"methodName":getCurrentEventModel.MethodName,@"updatedtime":getCurrentEventModel.UpdatedTime,@"systemcode":DefaultSystemCode,@"DataValue":getCurrentEventModel.DataValue};
    [BCNetAPIClient PostVideosAndImages:GetEventDataURL parameters:dic imageArray:_selectPhoteArray videoArray:_videoUrl.absoluteString success:^(id responseObjecet) {
        [SVProgressHUD showSuccessWithStatus:@"成功"];
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(NSError *error) {
        [SVProgressHUD showSuccessWithStatus:@"失败"];
        [self.navigationController popViewControllerAnimated:YES];
    }];
}

- (NSString *)dataValueJson {

    _StationModel.EventType  = [NSString stringWithFormat:@"%ld",(long)_typeInt];
    _StationModel.DutyMonitor      = self.dutyStationmaster.desTextV.text;
    _StationModel.OccurTime        = self.timeView.directionLabel.text;
    _StationModel.EventDescription = self.eventDescripV.desTextV.text;
    _StationModel.TollStationName  = self.stationV.directionLabel.text;
    
//    AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//    NSString *stationStr = _StationModel.
//    for (<#type *object#> in <#collection#>) {
//        <#statements#>
//    }
//    
 //   NSLog(@"%@",self.stationV.directionLabel.text);
    NSMutableDictionary *dic=_StationModel.mj_keyValues;
    NSString *modelStr=[dic mj_JSONString];
    
    ParModel *model=[[ParModel alloc] init];
    model.key=@"TollStationEventInfo";
    model.value=modelStr;
    
    NSMutableDictionary *jsonDic=model.mj_keyValues;
    NSString *json=[jsonDic mj_JSONString];
    
    NSString *str=@"[";
    NSString *temp=[str stringByAppendingString:json];
    NSString *str1=@"]";
    NSString *JsonString=[temp stringByAppendingString:str1];
    
    return JsonString;
}

- (void) setUpUI {
    self.view.backgroundColor = [UIColor colorWithRed:226.0 / 255 green:230.0 / 255 blue:240.0 / 255 alpha:1];
    self.wrapperView = [UIView new];
    self.wrapperView.backgroundColor = [UIColor colorWithRed:239.0 / 255 green:239.0 / 255 blue:249.0 / 255 alpha:0.8];
    [self.scroollView addSubview:self.wrapperView];
    [self setUpContainerV];
    [self setUpStationV];
    [self setUpEventTypeV];
    [self setUpDutyStationmaster];
    [self setUpTimeView];
    [self setUpEventDescripV];
    [self setUpPicAndVideoV];
    
    self.wrapperView.sd_layout
    .leftEqualToView(self.scroollView)
    .rightEqualToView(self.scroollView)
    .topEqualToView(self.scroollView)
    ;
    [self.containerV setupAutoHeightWithBottomView:self.eventDescripV bottomMargin:10]   ;
    [self.wrapperView setupAutoHeightWithBottomView:self.picAndVideoV bottomMargin:10]   ;
    [self.scroollView setupAutoContentSizeWithBottomView:self.wrapperView bottomMargin:0];
}

- (void) setUpContainerV {
    self.containerV = [[UIView alloc] init];
    [self.wrapperView addSubview:self.containerV];
    self.containerV.sd_layout
    .leftSpaceToView(self.wrapperView, 0)
    .rightSpaceToView(self.wrapperView, 0)
    .topSpaceToView(self.wrapperView, 0)
    .autoHeightRatio(0)
    ;
}
#pragma   设置UI

- (void) setUpStationV {
    self.stationV = [[ChooseDirectionView alloc] initWithDefalutHeight:40 title:@"收  费  站:"];
//    self.stationV.backgroundColor = [UIColor blueColor];
    [self.stationV.chooseDirectBtn addTarget:self action:@selector(stationBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.containerV addSubview:self.stationV];
    self.stationV.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .rightSpaceToView(self.containerV, 0)
    .topSpaceToView(self.containerV, 0)
    .autoHeightRatio(0)
    ;
}
- (void) setUpEventTypeV {
    self.eventTypeV = [[InProgressConstructPositionView alloc] initWithDefalutHeight:40.0 title:@"事 件 类 型:" isCanTouch:YES];
    [self.eventTypeV.middelBtn addTarget:self action:@selector(eventTypeDrop:) forControlEvents:UIControlEventTouchUpInside];
    [self.eventTypeV.rightBtn addTarget:self action:@selector(stencilBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.eventTypeV.rightLabel.text = @"事件模版";
    [self.containerV addSubview:self.eventTypeV];
    self.eventTypeV.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .rightSpaceToView(self.containerV, 0)
    .topSpaceToView(self.stationV, 0)
    .autoHeightRatio(0)
    ;
}
- (void) setUpDutyStationmaster {
    self.dutyStationmaster = [[UnStartEventView alloc]initWithDefalutHeight:40.0 title:@"值 班 站 长:"];
    [self.containerV addSubview:self.dutyStationmaster];
    self.dutyStationmaster.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .rightSpaceToView(self.containerV, 0)
    .topSpaceToView(self.eventTypeV, 0)
    .autoHeightRatio(0)
    ;
}

- (void) setUpTimeView {
    self.timeView = [[ChooseDirectionView alloc] initWithDefalutHeight:40 title:@"发 生 时 间:"];
    [self.timeView.chooseDirectBtn addTarget:self action:@selector(datePick:) forControlEvents:UIControlEventTouchUpInside];
    [self.containerV addSubview:self.timeView];
    self.timeView.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .rightSpaceToView(self.containerV, 0)
    .topSpaceToView(self.dutyStationmaster, 0)
    .autoHeightRatio(0)
    ;

}

- (void) setUpEventDescripV {
    self.eventDescripV = [[UnStartEventView alloc]initWithDefalutHeight:40.0 title:@"事 件 描 述:"];
    [self.containerV addSubview:self.eventDescripV];
    self.eventDescripV.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .rightSpaceToView(self.containerV, 0)
    .topSpaceToView(self.timeView, 0)
    .autoHeightRatio(0)
    ;
}
- (void) setUpPicAndVideoV {
    self.picAndVideoV = [[InProgressPicAndVideoView alloc] initWithDefalutHeight:40.0];
    [self.wrapperView addSubview:self.picAndVideoV];
    [self.picAndVideoV.picturesBtn addTarget:self action:@selector(photoesBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.picAndVideoV.videoBtn addTarget:self action:@selector(videoBtnClick) forControlEvents:UIControlEventTouchUpInside];
    self.picAndVideoV.sd_layout
    .leftSpaceToView(self.wrapperView, 0)
    .rightSpaceToView(self.wrapperView, 0)
    .topSpaceToView(self.containerV, 10)
    .autoHeightRatio(0)
    ;
}
#pragma  makr - 点击
- (void) stationBtnClick:(UIButton *)sender {
    _station.popoverPresentationController.sourceView = sender;
    _station.isStation = 1;
    _station.popoverPresentationController.delegate   = self;
    _station.popoverPresentationController.sourceRect = CGRectMake(130, 138, 0,0);
    _station.popoverPresentationController.permittedArrowDirections=NO;
    [self presentViewController:_station animated:YES completion:nil];
}
- (void) eventTypeDrop:(UIButton *)sender {
    __weak typeof(self) weakSelf = self;
    AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    EventTypeTableViewController *eventVC=[[EventTypeTableViewController alloc] init];
    eventVC.modalPresentationStyle = UIModalPresentationPopover;
    eventVC.LineBlock=^(NSInteger index, NSString *eventTypeStr){
        weakSelf.eventTypeV.middelLabel.text   = eventTypeStr;
//        weakSelf.eventDescripV.desTextV.text = nil;
        weakSelf.typeInt          = index;
        weakSelf.currentTemplateModel = myDelegate.allTollEvent[index - 1];
        if (weakSelf.currentTemplateModel.TemplateList.count > 0) {
            BDMTollEventTypeTemplateDefineInfoModel *model = _currentTemplateModel.TemplateList[0];
            [weakSelf.eventDescripV setContentString:model.TemplateContent];
            weakSelf.eventTypeV.rightLabel.text = model.TemplateName;
             weakSelf.eventDescripV.desTextV.text = model.TemplateContent;
        }
    };
    eventVC.popoverPresentationController.sourceView   = sender;
    eventVC.popoverPresentationController.delegate     = self;
    eventVC.popoverPresentationController.sourceRect   = CGRectMake(130, 138, 0, 0);
    eventVC.popoverPresentationController.permittedArrowDirections = NO;
    [self presentViewController:eventVC animated:YES completion:nil];
}

- (void) stencilBtnClick:(UIButton *)sender {
    if (self.eventTypeV.middelLabel.text.length > 0 ) {
        __weak typeof(self) weakSelf = self;
        if (_currentTemplateModel.TemplateList.count > 1) {
//            sender.selected = !sender.selected;
//            [sender adjustImagePositon:ROCameraPhotoesBtnRight spacing:5];
            
            NSMutableArray *tempNameArray = [[NSMutableArray alloc] init];
            NSMutableArray *contentArray  = [[NSMutableArray alloc] init];
            for (BDMTollEventTypeTemplateDefineInfoModel *tempateModel in _currentTemplateModel.TemplateList) {
                [tempNameArray addObject:tempateModel.TemplateName];
                [contentArray  addObject:tempateModel.TemplateContent];
            }
            DropDownBackView *backVc = [[DropDownBackView alloc] init];
            DrowDownViewController *stationListVC = [[DrowDownViewController alloc] init];
            stationListVC.view.width              = self.eventTypeV.rightBtn.width ;
            stationListVC.dataArray               = tempNameArray;
            stationListVC.view.height             = 44 * (tempNameArray.count);
            backVc.contentController              = stationListVC;
            stationListVC.indexClick              = ^(NSInteger tag, NSString *str) {
                weakSelf.eventTypeV.rightLabel.text = str;
                weakSelf.eventDescripV.desTextV.text             = contentArray[tag];
                [backVc dismiss];
            };
            [backVc showFrom:sender];
        }else {
            BDMTollEventTypeTemplateDefineInfoModel *model = _currentTemplateModel.TemplateList[0];
            weakSelf.eventDescripV.desTextV.text = model.TemplateContent;
        }
        
    }else {
        [SVProgressHUD showErrorWithStatus:@"请先选择事件类型"];
    }

}
- (void) setUpDatePicker:(UILabel *)label {
    
    EKDateTimePickerView *datepicker = [[EKDateTimePickerView alloc]initWithDatePosition:EKDatePositionMiddel CompleteBlock:^(NSDate *startDate) {
        _lastScrollDate = startDate;
        NSString *dateStr = [startDate stringWithFormat:@"yyyy-MM-dd HH:mm:ss" ];
    
        label.text = dateStr;
    }];
    datepicker.datePickerStyle = EKDateStyleShowYearMonthDayHourMinute;
    datepicker.themeColor      = [UIColor colorWithHexString:@"38b1dc"];
    if (label.text == nil) {
        _lastScrollDate = nil;
        [datepicker scrollToSepicefyDate:[RODateHelper dateWithOutTimeZoneFromString:label.text withFormat:nil] animated:NO];
    }
    
    if (_lastScrollDate != nil) {
        [datepicker scrollToSepicefyDate:_lastScrollDate animated:NO];
    }

    [datepicker show];
}

- (void)datePick:(UIButton *)btn {
    [self setUpDatePicker:self.timeView.directionLabel];
}

-(UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller {
    return UIModalPresentationNone;
}
#pragma mark -  图片和视频按钮点击
- (void) videoBtnClick {
    LittleVideoViewController *vc = [[LittleVideoViewController alloc] init];
    vc.delegate = self;
    [self.navigationController presentViewController:vc animated:YES completion:nil];
}

- (void) photoesBtnClick {
    if (self.selectPhoteArray.count >= 5) {
        [SVProgressHUD showErrorWithStatus:@"不能选择超过5张图"];
        return;
    }
    AJPhotoPickerViewController *picker = [[AJPhotoPickerViewController alloc] init];
    picker.maximumNumberOfSelection = 5 - self.selectPhoteArray.count;
    picker.multipleSelection        = YES;
    picker.assetsFilter             = [ALAssetsFilter allPhotos];
    picker.showEmptyGroups          = YES;
    picker.delegate                 = self;
    picker.selectionFilter          = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        return YES;
    }];
    
    [self presentViewController:picker animated:YES completion:nil];
}


#pragma mark- init
- (void) setUpArray {
    _selectPhoteArray = [[NSMutableArray alloc] init];
}

#pragma mark - BoPhotoPickerProtocol
- (void)photoPickerDidCancel:(AJPhotoPickerViewController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)photoPicker:(AJPhotoPickerViewController *)picker didSelectAssets:(NSArray *)assets {
    if ((self.selectPhoteArray.count + assets.count) > 5)  {
        [SVProgressHUD showSuccessWithStatus:@"不能超过5张"];
        return;
    }
    [picker dismissViewControllerAnimated:NO completion:nil];
    for (int i = 0; i < assets.count; i ++) {
        ALAsset *asset =  assets[i];
        UIImage *tempImg = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
        [self.selectPhoteArray addObject:tempImg];
    }
    _isFirstTime += 1;
    [self reConfigPhotoesView];
}

- (void) reConfigPhotoesView {
    for (UIImageView *imgV in self.photoesV.scrollV.subviews) {
        [imgV removeFromSuperview];
    }
    CGFloat x = 5;
    CGRect frame = CGRectMake(0, 0, 100, 100);
    
    self.photoesV.scrollV.contentSize = CGSizeMake(105 * self.selectPhoteArray.count + 5, 0);
    for (int i = 0 ; i < self.selectPhoteArray.count; i++) {
        frame.origin.x = x;
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
        [imageView setContentMode:UIViewContentModeScaleAspectFill];
        imageView.clipsToBounds          = YES;
        imageView.image                  = self.selectPhoteArray[i];
        imageView.tag                    = i;
        imageView.userInteractionEnabled = YES;
        [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showBig:)]];
        [self.photoesV.scrollV addSubview:imageView];
        
        x += frame.size.width+5;
    }
    if (_isFirstTime == 1) {
        if (_videoUrl) {
            [self reconfigVideoView];
        }else {
            [self.containerV setupAutoHeightWithBottomView:self.photoesV bottomMargin:10];
            [self.containerV layoutSubviews];
        }
    }
}

- (void)showBig:(UITapGestureRecognizer *)sender {
    NSInteger index = sender.view.tag;
    AJPhotoBrowserViewController *photoBrowserViewController = [[AJPhotoBrowserViewController alloc] initWithPhotos:self.selectPhoteArray index:index];
    photoBrowserViewController.delegate = self;
    //    UIImage *img = self.selectPhoteArray[index];
    //    [self.selectPhoteArray removeObjectAtIndex:index];
    _isFirstTime += 1;
    [self presentViewController:photoBrowserViewController animated:YES completion:nil];
}

- (void)photoBrowser:(AJPhotoBrowserViewController *)vc deleteWithIndex:(NSInteger)index {
    [self.selectPhoteArray removeObjectAtIndex:index];
    //    [self.photos removeObjectAtIndex:index];
    //    [self removeDeleteImages];
    [self reConfigPhotoesView];
}

- (void)photoBrowser:(AJPhotoBrowserViewController *)vc didDonePhotos:(NSArray *)photos {
    [vc dismissViewControllerAnimated:YES completion:nil];
    _isFirstTime += 1;
    [self reConfigPhotoesView];
}

- (void)photoPickerTapCameraAction:(AJPhotoPickerViewController *)picker {
    [self checkCameraAvailability:^(BOOL auth) {
        if (!auth) {
            NSLog(@"没有访问相机权限");
            return;
        }
        [picker dismissViewControllerAnimated:NO completion:nil];
        UIImagePickerController *cameraUI = [UIImagePickerController new];
        cameraUI.allowsEditing   = NO;
        cameraUI.delegate        = self;
        cameraUI.sourceType      = UIImagePickerControllerSourceTypeCamera;
        cameraUI.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;
        [self presentViewController: cameraUI animated: YES completion:nil];
    }];
}
- (void)checkCameraAvailability:(void (^)(BOOL auth))block {
    BOOL status = NO;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if(authStatus == AVAuthorizationStatusAuthorized) {
        status = YES;
    } else if (authStatus == AVAuthorizationStatusDenied) {
        status = NO;
    } else if (authStatus == AVAuthorizationStatusRestricted) {
        status = NO;
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if(granted){
                if (block) {
                    block(granted);
                }
            } else {
                if (block) {
                    block(granted);
                }
            }
        }];
        return;
    }
    if (block) {
        block(status);
    }
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
    UIImage *originalImage;
    if (CFStringCompare((CFStringRef) mediaType,kUTTypeImage, 0)== kCFCompareEqualTo) {
        originalImage = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        UIImageWriteToSavedPhotosAlbum(originalImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
- (void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo {
    if (!error) {
        //        NSLog(@"保存到相册成功");
        AJPhotoPickerViewController *picker = [[AJPhotoPickerViewController alloc] init];
        picker.maximumNumberOfSelection = 5;
        picker.multipleSelection        = YES;
        picker.assetsFilter             = [ALAssetsFilter allPhotos];
        picker.showEmptyGroups          = YES;
        picker.delegate                 = self;
        picker.selectionFilter          = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
            return YES;
        }];
        [self dismissViewControllerAnimated:NO completion:nil];
        [self presentViewController:picker animated:NO completion:nil];
    }else{
        //        NSLog(@"保存到相册出错%@", error);
    }
}
// *********** - 播放小视频 - *************
#pragma mark -littleVideoDelegate
- (void)finishLittleVideoViewControllerCapture:(NSURL *)filePath {
    _videoUrl = filePath;
    [self reconfigVideoView];
    [self crreatPlayViedeo:filePath];
}

- (void) reconfigVideoView {
    UIView *view;
    if (self.selectPhoteArray.count > 0) {
        view = self.photoesV;
    }else {
        view = self.eventDescripV;
    }
    
    if (_videoUrl) {
        self.videoView.sd_layout
        .widthIs([UIScreen mainScreen].bounds.size.width - 16)
        .heightIs(200)
        .topSpaceToView(view, 10)
        .centerXEqualToView(self.containerV)
        ;
        [self.containerV setupAutoHeightWithBottomView:self.videoView bottomMargin:10];
        [self.containerV layoutSubviews];
        [self.wrapperView layoutSubviews];
    }
}

- (void) crreatPlayViedeo:(NSURL *)videoUrl {
    _playItem = [AVPlayerItem playerItemWithURL:videoUrl];
    _player = [AVPlayer playerWithPlayerItem:_playItem];
    _playerLayer =[AVPlayerLayer playerLayerWithPlayer:_player];
    _playerLayer.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width - 16, 200);
    _playerLayer.videoGravity=AVLayerVideoGravityResizeAspectFill;//视频填充模式
    [self.videoView.layer addSublayer:_playerLayer];
    [_player play];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_player pause];
    _player = nil;
     SendNotify(GLStationEventReportNotification, self)
}

@end
